import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
};
Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    redirect: "/home"
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    children: [
      {
        path: '/home/searchPopup',
        name: 'SearchPopup',
        component: () => import(/* webpackChunkName: "searchPopup" */ '../views/SearchPopup.vue')
      }
    ],
    meta: {
      isShowTabber: true
    }
  },
  {
    path: '/user',
    name: 'user',
    component: () => import(/* webpackChunkName: "user" */ '../views/User.vue'),
    meta: {
      isShowTabber: true
    }
  },
  {
    path: '/topic',
    name: 'topic',
    component: () => import(/* webpackChunkName: "topic" */ '../views/Topic.vue'),
    meta: {
      isShowTabber: true
    }
  },
  {
    path: '/catalog',
    name: 'catalog',
    component: () => import(/* webpackChunkName: "catalog" */ '../views/Catalog.vue'),
    meta: {
      isShowTabber: true
    }
  },

  {
    path: '/cart',
    name: 'cart',
    component: () => import(/* webpackChunkName: "cart" */ '../views/Cart.vue'),
    meta: {
      isShowTabber: true
    }
  },
  {
    path: '/productDetail',
    name: 'ProductDetail',
    component: () => import(/* webpackChunkName: "productDetail" */ '../views/ProductDetail.vue'),
    mate: {
      isShowTabber: false
    }
  },
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由拦截/路由守卫，在跳转路由之前拦截写来，判断是否能够获取到token
router.beforeEach((to, from, next) => {
  // 简单理解，每一次跳转之前都会执行这个函数
  // to是要去往的路由对象 (to.path == "/cart" 假如成立，就跳出提示框)
  // from 是从哪里出发的这个路由对象
  console.log("to", to);
  console.log("from", from);

  let token = localStorage.getItem("token");
  console.log("token值是:", token);
  if (to.path == "/cart") {
    if (token) {
      next()
    } else {
      // 假如没有登录，就跳转到用户页面
      Vue.prototype.$toast("请先登录！")
      // 跳转到"我的"页面
      setTimeout(() => {
        next("/user")
      }, 1000)
    }
    return
  }
  next() // 必须要调用next() 才能到达要跳转到的这个页面
})

export default router
